import { defineStore } from 'pinia'
import { login as loginApi, getUserProfile } from '@/api/user'
import { getCurrentUserAvatar, buildAvatarUrl } from '@/api/avatar'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null,
    isLoggedIn: false,
    // 头像相关状态
    avatarCache: new Map(), // 用户头像缓存
    currentUserAvatar: '', // 当前用户头像
    avatarLoading: false // 头像加载状态
  }),

  actions: {
    // 登录
    async login(loginData) {
      try {
        const response = await loginApi(loginData)
        const { token } = response.data
        
        this.token = token
        this.isLoggedIn = true
        
        // 保存token到localStorage
        localStorage.setItem('token', token)
        
        // 获取用户信息
        await this.fetchUserInfo()
        
        // 获取用户头像
        await this.fetchCurrentUserAvatar()
        
        return response
      } catch (error) {
        this.logout()
        throw error
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await getUserProfile()
        this.userInfo = response.data
        
        // 更新头像缓存
        if (response.data.avatar && response.data.id) {
          this.setAvatarCache(response.data.id, response.data.avatar)
        }
        
        return response
      } catch (error) {
        this.logout()
        throw error
      }
    },

    // 获取当前用户头像
    async fetchCurrentUserAvatar() {
      if (!this.isLoggedIn) {
        this.currentUserAvatar = '/default-avatar.svg'
        return
      }
      
      try {
        this.avatarLoading = true
        const response = await getCurrentUserAvatar()
        
        if (response.data && response.data.avatarUrl) {
          this.currentUserAvatar = response.data.avatarUrl
          
          // 更新用户信息中的头像
          if (this.userInfo) {
            this.userInfo.avatar = response.data.avatarUrl
          }
          
          // 更新头像缓存
          if (response.data.userId) {
            this.setAvatarCache(response.data.userId, response.data.avatarUrl)
          }
        }
        
        return response
      } catch (error) {
        // 对于网络错误或服务器错误，使用默认头像
        if (error.response?.status === 401) {
          console.log('用户未授权，使用默认头像')
          this.currentUserAvatar = '/default-avatar.svg'
          // 可能需要重新登录
        } else {
          console.error('获取用户头像失败:', error)
          this.currentUserAvatar = '/default-avatar.svg'
        }
      } finally {
        this.avatarLoading = false
      }
    },

    // 更新用户头像
    updateUserAvatar(avatarUrl) {
      this.currentUserAvatar = avatarUrl
      
      // 更新用户信息中的头像
      if (this.userInfo) {
        this.userInfo.avatar = avatarUrl
        // 更新头像缓存
        this.setAvatarCache(this.userInfo.id, avatarUrl)
      }
    },

    // 设置头像缓存
    setAvatarCache(userId, avatarUrl) {
      if (userId && avatarUrl) {
        this.avatarCache.set(String(userId), {
          avatarUrl,
          timestamp: Date.now()
        })
      }
    },

    // 获取头像缓存
    getAvatarCache(userId) {
      const cache = this.avatarCache.get(String(userId))
      
      // 检查缓存是否过期（1小时）
      if (cache && Date.now() - cache.timestamp < 3600000) {
        return cache.avatarUrl
      }
      
      return null
    },

    // 清除头像缓存
    clearAvatarCache(userId = null) {
      if (userId) {
        this.avatarCache.delete(String(userId))
      } else {
        this.avatarCache.clear()
      }
    },

    // 登出
    logout() {
      this.token = ''
      this.userInfo = null
      this.isLoggedIn = false
      this.currentUserAvatar = ''
      
      // 清除缓存
      this.clearAvatarCache()
      
      // 清除localStorage
      localStorage.removeItem('token')
    },

    // 初始化用户状态
    async initUserState() {
      if (this.token) {
        try {
          await this.fetchUserInfo()
          this.isLoggedIn = true
          
          // 初始化头像
          await this.fetchCurrentUserAvatar()
        } catch (error) {
          this.logout()
        }
      }
    },

    // 异步获取用户头像（带缓存）
    async fetchUserAvatar(userId) {
      if (!userId) return '/default-avatar.svg'
      
      // 先检查缓存
      const cached = this.getAvatarCache(userId)
      if (cached) {
        return buildAvatarUrl(cached)
      }
      
      try {
        const response = await getUserAvatar(userId)
        
        if (response.data && response.data.avatarUrl) {
          // 更新缓存
          this.setAvatarCache(userId, response.data.avatarUrl)
          return buildAvatarUrl(response.data.avatarUrl)
        }
      } catch (error) {
        console.warn(`获取用户${userId}头像失败:`, error.message)
      }
      
      return '/default-avatar.svg'
    }
  },

  getters: {
    // 获取用户头像
    avatar: (state) => {
      return buildAvatarUrl(state.currentUserAvatar || state.userInfo?.avatar || '/default-avatar.svg')
    },

    // 获取用户昵称
    nickname: (state) => {
      return state.userInfo?.nickname || '未设置昵称'
    },

    // 获取用户名
    username: (state) => {
      return state.userInfo?.username || ''
    },

    // 获取用户ID
    userId: (state) => {
      return state.userInfo?.id || null
    },

    // 根据用户ID获取头像
    getAvatarByUserId: (state) => (userId) => {
      // 先从缓存中查找
      const cached = state.avatarCache.get(String(userId))
      if (cached && Date.now() - cached.timestamp < 3600000) {
        return buildAvatarUrl(cached.avatarUrl)
      }
      
      // 如果是当前用户
      if (userId === state.userInfo?.id) {
        return buildAvatarUrl(state.currentUserAvatar || state.userInfo?.avatar)
      }
      
      return '/default-avatar.svg'
    }
  }
}) 